import 'node-assist'
import CommonUtil from 'js-common-modules/lib/node/utils/CommonUtil'
import BitcoinWalletHelper from 'js-common-modules/lib/node/helpers/bitcoin/BitcoinWalletHelper'

global['logger'] = console

const config = {
  version: 'testnet',
  wif: 'cUEHLwt7e7rXFoATPKyyWEGJv3BTznPSz79aFBWfyAHMzemCADCL',
  utxos: [
    {
      txId: '534bf6169a2b1a2feec8cab37030b8956f384b833d526a9423fec7c569c24e0d',
      outputIndex: 0,
      outputBalance: 0.65,
      sequence: 0
    },
  ],
  targetAddress: 'mpcFhXGhao3J7xaP1eCTKZP8t5vzN5jwND',
  amount: null,
  fee: 0.001
}


CommonUtil.startAsyncMethod(async () => {
  const bitcoinWalletHelper = new BitcoinWalletHelper()
  const utxos = []
  let sum = '0'
  for (let utxo of config['utxos']) {
    utxos.push({
      utxoTxId: utxo['txId'],
      utxoOutputIndex: utxo['outputIndex'],
      utxoBalance: utxo['outputBalance'],
      wif: config['wif'],
      sequence: utxo['sequence']
    })
    sum = sum.add(utxo['outputBalance'].toString())
  }
  if (config['amount'] === null) {
    config['amount'] = sum.sub(config['fee'].toString())
  }
  const result = await bitcoinWalletHelper.buildTransaction(utxos, [
    {
      address: config['targetAddress'],
      amount: config['amount']
    }
  ], config['fee'], bitcoinWalletHelper.wifToAddress(config['wif'], config['version']), config['version'], true)

  logger.error(result)
})

// { txHex: '02000000010d4ec269c5c7fe23946a523d834b386f95b83070b3cac8ee2f1a2b9a16f64b53000000006b483045022100f45929a478ed8a868d02875b90e3cd08a754c7d08bc03e8f3b7cfc300ce133fc02205b2f7319bd2c06f8c1bf08d939cee161a02945baf0589b1ca0dfc6029521dfb601210368611bb1aff444be1c11717985d5bbdbe79542e1469b997b7a0d63ac1c7615380000000001a04bde03000000001976a91463b9bd92a3605869946677cf24f38f572fd6603788ac00000000',
//   txId: '7ca8e64636b07ab090d0a96419392ae2bd10da42009f993a05566c4bfd15b0f6' }


